package com.hzcx.app.simplechat.ui.setting;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.ui.chat.event.ChatShareUserEvent;
import com.hzcx.app.simplechat.ui.friend.FriendSearchActivity;
import com.hzcx.app.simplechat.ui.friend.adapter.FriendLableListAdapter;
import com.hzcx.app.simplechat.ui.friend.adapter.FriendSortAdapter;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendLableListBean;
import com.hzcx.app.simplechat.ui.friend.dialog.FriendSortDialog;
import com.hzcx.app.simplechat.ui.setting.contract.GroupMsgFriendListContract;
import com.hzcx.app.simplechat.ui.setting.presenter.GroupMsgFriendListPresenter;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.dp.DpUtils;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.view.SideLetterBar;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 群发助手，搜索好友界面
 */
public class GroupMsgFriendListActivity extends BaseActivity<GroupMsgFriendListPresenter> implements GroupMsgFriendListContract.View {

    public static final String INTENT_TAG = "INTENT_TAG";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.rv_friend)
    RecyclerView rvFriend;
    @BindView(R.id.side_bar)
    SideLetterBar sideBar;
    @BindView(R.id.tv_overlay)
    TextView tvOverlay;


    private List<FriendCityBean> friendData;
    private FriendSortAdapter friendAdapter;
    private List<FriendLableListBean> lableData;
    private FriendLableListAdapter lableAdapter;

    @Override
    public int getLayout() {
        return R.layout.activity_group_msg_friend_list_old;
    }

    @Override
    public void initPresenter() {
        mPresenter = new GroupMsgFriendListPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("选择好友");
        tvTitleRight.setText("全选");
        sideBar.setVisibility(View.GONE);

        friendData = new ArrayList<>();
        friendAdapter = new FriendSortAdapter(friendData, true);
        rvFriend.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvFriend.setAdapter(friendAdapter);
    }

    @Override
    public void initData() {
        showLoading();
        addHeader();

        // 会员才有按标签群发
        if (UserInfoUtil.getUserIsVip()) {
            mPresenter.getFriendLableList(this);
        } else {
            mPresenter.getFriendList(this, 1, false);
        }

        friendAdapter.setOnItemClickListener((adapter, view, position) -> {
            int pos = position;
            friendData.get(pos).setChecked(!friendData.get(pos).isChecked());
            friendAdapter.notifyDataSetChanged();
            setNum();
        });
    }

    @OnClick({R.id.tv_title_right, R.id.tv_next})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_title_right: // 全选
                if (friendData == null || friendData.size() <= 0) {
                    return;
                }
                allChecked();
                friendAdapter.notifyDataSetChanged();
                break;

            case R.id.tv_next:
                toNext();
                break;
        }
    }

    /**
     * 全选
     */
    private void allChecked() {
        for (FriendLableListBean bean : lableData) {
            bean.setChecked(true);
        }
        for (FriendCityBean bean : friendData) {
            bean.setChecked(true);
        }
        friendAdapter.notifyDataSetChanged();
        lableAdapter.notifyDataSetChanged();
        setNum();
    }

    /**
     * 下一步
     */
    private void toNext() {
        if (setNum() <= 0) {
            showError("请选择要发送的好友");
            return;
        }
        int count = 0;
        String names = "";
        String hxUsernames = "";
        String ids = "";

        for (FriendLableListBean bean : lableData) {
            if (bean.isChecked()) {
                count += bean.getMember_count();
                names += bean.getMembers_name();
                hxUsernames += bean.getMembers_hxusername();
                ids += bean.getMember_ids();
            }
        }

        for (FriendCityBean bean : friendData) {
            if (bean.isChecked()) {
                // TODO: 2021/1/12  多写这一段是为了去重
                boolean isAdd = true;
                if (ids.contains(bean.getMember_id() + "")) {
                    isAdd = false;
                }
                if (isAdd) {
                    count++;
                    String name = EmptyUtils.isNotEmpty(bean.getRemarks_name()) ? bean.getRemarks_name() : bean.getNickname();
                    names = names + "," + name;
                    hxUsernames = hxUsernames + "," + bean.getHxusername();
                    ids = ids + "," + bean.getMember_id();
                }
            }
        }

        startActivity(new Intent(this, GroupMessageSendActivity.class)
                .putExtra(GroupMessageSendActivity.INTENT_COUNT, count)
                .putExtra(GroupMessageSendActivity.INTENT_NAMES, names)
                .putExtra(GroupMessageSendActivity.INTENT_HXUSERNAME, hxUsernames)
                .putExtra(GroupMessageSendActivity.INTENT_IDS, ids));
    }

    /**
     * 好友列表获取成功
     *
     * @param data
     */
    @Override
    public void friendListResult(List<FriendCityBean> data, int type) {
        hideLoading();
        try {
            friendData.clear();
            friendData.addAll(data);
            friendAdapter.notifyDataSetChanged();
            if (UserInfoUtil.getUserIsVip()) {
                llContent.setVisibility(View.VISIBLE);
            }
            if (type == 1) {
                tvSort.setText("按在线时间排序");
            } else {
                tvSort.setText("按添加时间排序");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 标签列表获取成功
     *
     * @param data
     */
    @Override
    public void lableResult(List<FriendLableListBean> data) {
        try {
            lableData.clear();
            lableData.addAll(data);
            lableAdapter.notifyDataSetChanged();
            mPresenter.getFriendList(this, 1, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置选中数量
     */
    private int setNum() {
        int num = 0;
        for (FriendLableListBean bean : lableData) {
            if (bean.isChecked()) {
                num++;
            }
        }
        for (FriendCityBean bean : friendData) {
            if (bean.isChecked()) {
                num++;
            }
        }
        if (num > 0) {
            tvNext.setText("下一步(" + num + ")");
        } else {
            tvNext.setText("下一步");
        }
        return num;
    }

    /**
     * 搜索好友返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void FriendSearchClcik(ChatShareUserEvent event) {
        if (event.getTag() == 10) {
            for (FriendCityBean bean : friendData) {
                if (event.getBean().getMember_id() == bean.getMember_id()) {
                    bean.setChecked(!bean.isChecked());
                }
            }
            friendAdapter.notifyDataSetChanged();
            setNum();
        }
    }

    /**
     * 添加头部
     */
    private ConstraintLayout consSearch;
    private RecyclerView rvFriendLable;
    private TextView tvSort;
    private LinearLayout llContent;

    private void addHeader() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_home_header, null);
        consSearch = view.findViewById(R.id.cons_search);
        rvFriendLable = view.findViewById(R.id.rv_friend_lable);
        tvSort = view.findViewById(R.id.tv_sort);
        llContent = view.findViewById(R.id.ll_content);

        lableData = new ArrayList<>();
        lableAdapter = new FriendLableListAdapter(lableData, false);
        rvFriendLable.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvFriendLable.setAdapter(lableAdapter);

        lableAdapter.setOnItemChildClickListener((adapter, itemView, position) -> {
            switch (itemView.getId()) {
                case R.id.cons_content:
                    lableOnClick(position);
                    setNum();
                    break;
            }
        });

        // 排序标题点击
        tvSort.setOnClickListener(view12 -> showSortDialog());

        consSearch.setOnClickListener(view1 -> startActivity(new Intent(GroupMsgFriendListActivity.this, FriendSearchActivity.class)
                .putExtra(FriendSearchActivity.INTENT_TAG, 10)));

        friendAdapter.addHeaderView(view);
    }

    /**
     * 标签列表点击
     */
    private void lableOnClick(int pos) {
        FriendLableListBean lableBean = lableData.get(pos);
        for (FriendCityBean bean : friendData) {
            if (lableBean.getMember_ids().contains(bean.getMember_id() + "")) {
                if (lableBean.isChecked()) {
                    bean.setChecked(false);
                } else {
                    bean.setChecked(true);
                }
            }
        }
        lableData.get(pos).setChecked(!lableData.get(pos).isChecked());
        lableAdapter.notifyDataSetChanged();
        friendAdapter.notifyDataSetChanged();
    }

    /**
     * 弹出排序选择框
     */
    private void showSortDialog() {
        int[] location = new int[2];
        tvSort.getLocationInWindow(location);
        LogUtils.d("x:" + location[0]);
        LogUtils.d("y:" + location[1]);
        FriendSortDialog sortDialog = new FriendSortDialog(this, DpUtils.dp2px(this, 20),
                location[1] + DpUtils.dp2px(this, 10), new FriendSortDialog.OnFriendSortMenuListener() {
            @Override
            public void sortType(int type) {
                mPresenter.getFriendList(GroupMsgFriendListActivity.this, type, true);
            }
        });
        sortDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
